// pages/good/detail.js
const { ticketadd } = require("../../request/api");
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    uid: 9,
    page: 1,
    page_size: 15,
    if_show_box: false,
    cart_num: 1,
    goods_id: 0,
    current_no: 1,
    total_no: '',
    good_list: [],
    if_show_qr_code_layer: false,
    qr_code_url: '',
    image_detail_list: [],
    if_show_share_box: false,
    detail_data: '',
    if_show_mask: false,
    chosen_specification_index: 0,
    ticket_list: [],
    specification_data: {
      product: [{
        name: '规格1'
      }, {
        name: '规格2'
      }, {
        name: '规格3'
      }, {
        name: '规格3'
      },]
    },
    show_cart_or_buying: 0,
    if_show_ticket_box: false,
    entrance: '',
    day: '',
    hour: "",
    minute: "",
    second: "",
    leftTime: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.init_data(options)
    this.get_good_detail()
    this.get_goods_list()
    this.get_ticket_list()
    this.set_title()
  },

  // 初始化数据
  init_data(options) {
    this.setData({
      uid: util.getAppValue(App.globalData.uid),
      goods_id: options.id,
      entrance: options.entrance,
    })
    //打印entrance
  },
  set_title() {
    if (this.data.entrance == 'hot_good_around') {
      wx.setNavigationBarTitle({
        title: '爆品详情',
      })
    }
  },
  // 优惠券
  get_ticket_list() {
    let params = {
      uid: this.data.uid,
      pageSize: 3,
    }
    request.post(api.ticketlist, params).then(res => {
      this.setData({
        ticket_list: res
      })
    })
  },
  // 计算剩余时间
  count_time(end_time) {
    //获取当前时间
    var date = new Date();
    var now = date.getTime();
    //设置截⽌时间
    var str = end_time;
    console.log(end_time);
    var endDate = new Date(str);
    var end = endDate.getTime();
    console.log(now);
    console.log(end);
    //时间差
    var leftTime = end - now;
    //定义变量 d,h,m,s保存倒计时的时间
    var d, h, m, s;
    console.log(leftTime);
    if (leftTime >= 0) {
      d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      m = Math.floor(leftTime / 1000 / 60 % 60);
      s = Math.floor(leftTime / 1000 % 60);
    }
    else {
      return
    }
    // 将倒计时赋值到div中
    this.setData({
      day: d + '天',
      hour: h + "时",
      minute: m + "分",
      second: s + "秒",
      leftTime,
    })
    setTimeout(() => this.count_time(end_time), 1000);
  },

  get_good_detail() {
    let params = {
      id: this.data.goods_id,
      uid: this.data.uid,
    }
    request.post(api.goods_details, params).then(res => {
      this.setData({
        detail_data: res
      })
      this.get_detail_image(res.content)
      this.load_acode()
      if (this.data.entrance == 'promotion') {
        this.count_time(res.ext_skill.end_time)
      }
    })
  },
  go_detail(e) {
    let id = e.detail.currentTarget.dataset.id
    if (!id) {
      id = 10
    }
    wx.navigateTo({
      url: '/pages/good/detail?id=' + id,
    })
  },
  go_shop(e) {

    wx.navigateTo({
      url: '/pages/shop/shop'
    })
  },
  go_ticket(e) {

    wx.navigateTo({
      url: '/pages/ticket/ticket'
    })
  },
  cart_add() {
    util.showLoading("正在添加")
    let params = {
      // goods_num: this.data.cart_num,
      goods_id: this.data.goods_id,
      uid: this.data.uid
    }
    request.post(api.cart_add, params).then(res => {
      this.setData({
        if_show_box: false
      })
      util.showToast("已加入购物车")
    })
  },
  get_detail_image(image_str_url) {
    let image_str_url_list = image_str_url.split(',')
    image_str_url_list = this.delete_shop_str(image_str_url_list)
    this.setData({
      image_detail_list: image_str_url_list
    })
  },
  delete_shop_str(image_str_url_list) {
    for (let i = 0; i < image_str_url_list.length; i++) {
      const first_string = image_str_url_list[i].substring(0,5)
      console.log(first_string)
      if (first_string === '/shop') {
        image_str_url_list[i] =  'http://img.gangjinhui.cn' + image_str_url_list[i]
      }
      image_str_url_list[i] = image_str_url_list[i].replace('/data/', '/')
    }
    return image_str_url_list
  },

  collecting(e) {
    let is_follow = e.currentTarget.dataset.is_follow
    let gid = e.currentTarget.dataset.id
    let if_register = App.globalData.if_register
    if (!if_register) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
    else {
      let params = {
        uid: this.data.uid,
        gid
      }
      if (is_follow == 0) {
        this.follow_add(params)
      }
      else {
        this.follow_delete(params)
      }
    }
  },

  get_new_goods_list() {
    let params = {
      page: this.data.page,
      pageSize: this.data.page_size,
      uid: this.data.uid
    }
    let old_list = this.data.good_list
    request.post(api.goods_more, params).then(res => {
      if (res.length != 0) {
        let new_list = old_list.concat(res)
        this.setData({
          good_list: new_list
        })
      }
      else {
        this.setData({
          noMoreData: true
        });
        util.showToast('暂无更多商品了');
      }
    })
  },

  get_goods_list() {
    let params = {
      page: this.data.page,
      pageSize: this.data.page_size,
      uid: this.data.uid
    }
    request.post(api.goods_more, params).then(res => {
      this.setData({
        good_list: res
      })
    })
  },

  swiper_no_change(e) {
    this.setData({
      current_no: e.detail.current + 1
    })
  },

  show_box(e) {
    let show_cart_or_buying = e.currentTarget.dataset.show_cart_or_buying
    this.setData({
      if_show_box: true,
      show_cart_or_buying
    })
  },

  clear_mask() {
    this.setData({
      if_show_box: false,
      if_show_share_box: false,
      if_show_qr_code_layer: false,
      if_show_mask: false,
      if_show_ticket_box: false,
    })
  },

  hide_box() {
    this.setData({
      if_show_box: false,
      if_show_share_box: false,
      if_show_qr_code_layer: false,
      if_show_mask: false,
      if_show_ticket_box: false,
    })
  },

  minus() {
    this.setData({
      cart_num: --this.data.cart_num
    })
  },

  plus() {
    this.setData({
      cart_num: ++this.data.cart_num
    })
  },

  confirm_cart() {
    util.showLoading("正在添加")
    let params = {
      // goods_num: this.data.cart_num,
      goods_id: this.data.goods_id,
      uid: this.data.uid
    }
    request.post(api.cart_add, params).then(res => {
      this.setData({
        if_show_box: false,
      })
      util.showToast("已加入购物车")
    })
  },

  show_share_box() {
    this.setData({
      if_show_share_box: true
    })
  },

  go_cart() {
    console.log(1);
    wx.switchTab({
      url: '/pages/home/cart',
    })
  },

  confirm_buying() {
    let url = ''
    // this.setData({
    //   if_show_box:false,
    // })
    if (this.data.entrance == 'hot_good_around') {
      url = '/pages/order/pay?type=1' + '&good_id=' + this.data.goods_id
    }

    // let url = '/pages/order/pay?type=1' + '&good_id=' + this.data.goods_id

    if (this.data.entrance == 'point') {
      url = '/pages/order/pay?type=10' + '&good_id=' + this.data.goods_id
    }
    wx.navigateTo({
      url,
    })
  },

  choose_specification(e) {
    let chosen_specification_index = e.currentTarget.dataset.index
    this.setData({
      chosen_specification_index
    })
  },
  go_contact() {

  },

  go_vip() {
    let url = '/pages/vip/vip'
    wx.navigateTo({
      url,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var noMoreData = this.data.noMoreData;
    if (!noMoreData) {
      var pageno = this.data.page;
      pageno++;
      this.setData({
        page: pageno
      });
      this.get_new_goods_list();
    }
  },
  get_qr_code() {
    let params = {
      sid: this.data.sid
    }
    this.setData({
      if_show_share_box: false,
      if_show_mask: true,
      if_show_qr_code_layer: true,
    })
    request.post(api.qr_code, params).then(res => {
      this.setData({
        qr_code_url: res.img
      })
    })
  },
  // save_qr_code() {
  //   this.setData({
  //     if_show_mask: false,
  //     if_show_qr_code_layer: false,
  //   })
  //   wx.showLoading({
  //     title: '下载中',
  //   })
  //   wx.downloadFile({
  //     url: this.data.qr_code_url,
  //     success: res=>{
  //       wx.saveImageToPhotosAlbum({
  //         filePath: res.tempFilePath,
  //         success: res=>{
  //           wx.hideLoading()
  //           wx.showModal({
  //             content: '保存成功'
  //           })
  //         }
  //       })
  //     }
  //   })
  // },



  // 优惠券相关函数
  show_ticket() {
    this.setData({
      if_show_ticket_box: true,
      if_show_mask: true
    })
  },

  add_ticket(e) {
    let tid = e.currentTarget.dataset.tid
    let params = {
      uid: this.data.uid,
      type: 2,
      tid,
      // page: 1,
      // pageSize: 10,
    }
    request.post(api.ticketadd, params).then(res => {
      console.log(res);
      util.showToast("领取成功")
    })
  },


  load_acode() {
    let id = this.data.detail_data.id
    let uid = this.data.uid
    let sid = uid + 'a' + id
    this.setData({
      sid,
    })
    // let acode_url = "https://api.gzzsu.com/pq01/wxacodeshow?sid=" + sid
    // this.setData({
    //   acode_url
    // })
  }
  ,
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    var sid = this.data.sid
    var title = this.data.detail_data.name;
    var share_path = '/pages/home/acode?sid=' + sid;
    var shareObj = {
      title: title,
      path: share_path,
      imageUrl: '',
      success: function (res) {
        if (res.errMsg == 'shareAppMessage:ok') {
          Util.showToast('分享成功');
        }
      },
      fail: function () {
        Util.showToast('分享失败');
      },
    };
    return shareObj;
  }
})